import Utils from "@/utils/basic.utils";
export function isIdCard(val) {
    return /^\d{15}|\d{18}$/.test(val)
}
export function isIp(val) {
    return /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.test(val);
}
export function isUrl(val) {
    return /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(val);
}
export function isReg(val, reg) {
    return new RegExp(reg || '').test(val);
}
export function isWord(val) {
    return /[a-zA-Z]/.test(val)
}
export function isPhone(val) {
    return /^1[3|4|5|7|8][0-9]{9}$/.test(val);
}
export function isEmail(val) {
    return /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/.test(val)
}
export function isBank(val) {
    return /^([1-9])(\d{14}|\d{18})$/.test(val)
}
export function isChinese(val){
    return /^[\u4e00-\u9fa5]+$/.test(val)
}
export function isZip(val) {
    return /[1-9]\d{5}(?!\d)/.test(val);
}
export function isLength(val, length) {
    return val.length <= length
}

export const ValidateLib = {
    idCard: {validate: isIdCard, message: (model) => '请输入正确的身份证号'}
    , ip: {validate: isIp, message: (model) => '请输入正确的ip地址'}
    , url: {validate: isUrl, message: (model) => '请输入正确的url地址'}
    , regexp: {validate: isReg, message: (model) => `不符合规则[${model.validateValue}]`}
    , word: {validate: isWord, message: (model) => '请输入字母'}
    , phone: {validate: isPhone, message: (model) => '请输入正确的手机号'}
    , email: {validate: isEmail, message: (model) => '请输入正确的邮箱'}
    , bank: {validate: isBank, message: (model) => '请输入正确的银行卡号'}
    , chinese: {validate: isChinese, message: (model) => '请输入中文'}
    , zip: {validate: isZip, message: (model) => '不符合规则'}
    , len: {validate: isLength, message: (model) => '输入的长度错误'}
}

export function getValidator(type, model) {
    let validate = ValidateLib[type];
    if(validate) {
        return (rule, val) => {
            if(!val) {
                if(rule.required) {
                    return Promise.reject(`${model.title}必填`)
                } else {
                    return Promise.resolve();
                }
            } else {
                if (validate.validate(val, model.validateValue)) {
                    return Promise.resolve();
                } else {
                    return Promise.reject(validate.message(model))
                }
            }
        }
    } else {
        return () => Promise.resolve();
    }
}
